<?php


namespace app\controller;

use think\facade\Db;
use think\facade\View;

class Books
{
    public function bookindex()
    {
        return view();
    }

    //数据接口：分页返回所有图书
    public function allbook()
    {
        $page = input("page");//页号
        $limit = input("limit");//每条页数
        $offset = ($page - 1) * $limit;//偏移量

        //student总记录数
        $count=Db::name("book")->count();

        //部分数据
        $arr = Db::name("book")
            ->limit($offset, $limit)
            ->select()
            ->toArray();

        $data = [
            "code" => 0,
            "mes" => "",
            "count" => $count,//记录总数
            "data" => $arr,
        ];
        return json($data);
    }

    //数据接口：删除图书
    public function delete()
    {
        $id = input("id");//接受前端传回来的id
        $count = Db::name("book")
            ->where('id', "in", $id)
            ->delete();
        if ($count > 0) {
            //删除成功
            return "success";
        } else {
            //删除失败
            return "fail";
        }
    }

    //显示编辑页面
    public function edit()
    {
        $id = input("id");

        $data = Db::name("book")
            ->where("id", $id)
            ->find();

        View::assign("book", $data);
        return view();
    }

    //编辑后的提交
    public function editSubmit()
    {
        //接收数据
        $id = input("id");
        $number = input("number");
        $category = input("category");
        $name = input("name");
        $writer = input("writer");

        $data = [
            'number' => $number,
            'category' => $category,
            'name' => $name,
            'writer' => $writer
        ];

        $count = Db::name("book")
            ->where("id", $id)
            ->update($data);
        if ($count > 0) {
            return 'success';
        } else {
            return 'fail';
        }
    }

    //显示表单
    public function showbook()
    {
        return view();
    }

    public function add()
    {
        $number = input("number");
        $category = input("category");
        $name = input("name");
        $writer = input("writer");

        $data = [
            'number' => $number,
            'category' => $category,
            'name' => $name,
            'writer' => $writer
        ];
        $count = Db::name("book")->insert($data);
        if ($count > 0) {
            return 'success';
        } else {
            return 'fail';
        }
    }



    //输出表格样式的表
//    public function see()
//    {
//        $bok = Db::name( "book")
//            ->select()
//            ->toArray();
//        View::assign("books", $bok);
//        return view();
//    }
}
